#include "gui.h"

//si on utilise le GUI, ne pas appeler cette fonction avant le gtk_main
void msg(char *format,...)
{
	#ifdef DEBUG
		//initialisation des variables
		//le nouveau format qui aura "debug:" ajouté en tête
		char temp[130];
		char temp3[130];
		//le string final (cas de USE_GUI seulement)
		char* temp2;
		va_list args;
		va_start(args,format);
		//ajout de "debug:" en tete du message
		snprintf(temp,130,"debug:%s",format);
		#ifdef USE_GUI
			if(!gui_started)
			{
				snprintf(temp3,130,"debug_for_gui:%s",format);
				vprintf(temp3,args);
			}
			else
			{
				temp2 = strdup(temp);
				vsnprintf(temp2,130,temp,args);
				gtk_label_set_text(GTK_LABEL(debug_label),temp2);
				free(temp2);
			}
		#endif
		#ifdef USE_CONSOLE
			vprintf(temp,args);
		#endif
		va_end(args);
	#endif
}

//typiquement : filename : gui_settings.conf
int set_settings_file(char* filename)
{
	FILE* fp;
	char line[200];
	int using_default=0;
	char* fgets_result; //ne pas mettre à NULL
	char* name=NULL;
	char* value=NULL;
	int nb=0;
	if(filename == NULL)
	{
		filename = strdup("gui_settings.conf");
		using_default = 1;
	}
	msg("set_settings_file:using %s settings file : %s\n",((using_default) ? "default" : ""),filename);
	fp = fopen(filename,"r");
	if(!fp)
	{
		msg("set_settings_file:%s doesn't exist !\n");
		return 0;
	}
	while(!feof(fp))
	{
		fgets(line,200,fp);
		//enleve le \n
		if(line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0';
		name = strtok(line,":");
		//enleve les espaces de fin de texte
		while(name[strlen(name)-1]==' ')
			name[strlen(name)-1] = '\0';
		//msg("nom:%s\n",name);
		value = &(line[strlen(name)+1]);
		//eneleve les espaces de fin de texte
		while(value[strlen(name)-1]==' ')
			value[strlen(name)-1] = '\0';
		//msg("value:%s\n",value);
		strncpy(_settings[nb][0],name,MAX_SETTING_LENGTH);
		strncpy(_settings[nb][1],value,MAX_SETTING_LENGTH);
		nb+=1;
	}
	_nb_settings = nb;
	return 1;
}

char* get_setting(char* setting_name)
{
	int a;
	for(a=0;a<_nb_settings;a++)
	{
		if(strcmp(_settings[a][0],setting_name) == 0)
		{
			return _settings[a][1];
		}
	}
	msg("get_setting : %s not found\n",setting_name);
	return NULL;
}